package ihm.panel;

import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class BMPPlayer extends JPanel {
	
	private static final long serialVersionUID = 1L;
	
	//private KrakenClient client;
	
	public ImagePanel imgpanel = null;
	public static int ctr = 0;
	
	/**
	 * Constructeur.
	 */
	public BMPPlayer(/*KrakenClient client*/) {
		//this.client = client;
		
		setLayout(new BorderLayout());
		setSize(320, 240);

		imgpanel = new ImagePanel();
		add(imgpanel, BorderLayout.CENTER);
		
		//startPlayer(10, 0, 10000);
	}
	
	/**
	 * Démarre le lecteur.
	 * @param fps
	 * @param delay en ms
	 * @param time en ms
	 */
	/*public void startPlayer(int fps, int delay, final int time) {
		final long intervals = 1000/fps;
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				BufferedImage img = null;
			    try {
					//img = ImageIO.read(new File("test\\test"+ctr+".bmp"));
					
					// request new frame, method new frame ready?
			    	byte[] bmp = new byte[client.getData().length+client.getHeader_size()];
			    	System.arraycopy(client.getHeader(), 0, bmp, 0, client.getHeader_size());
			    	System.arraycopy(client.getData(), 0, bmp, client.getHeader_size(), client.getData().length);
			    	InputStream in = new ByteArrayInputStream(bmp);
					img = ImageIO.read(in);
				} catch (IOException e) {
					e.printStackTrace();
				}
				//ctr++;
				imgpanel.setImage(img);
				
				if(ctr*intervals >= time) {
					ctr = 0;
					cancel();
				}
			}
		};

		Timer timer = new Timer();
		timer.scheduleAtFixedRate(timerTask, delay, intervals);
	}*/
	
	public void nextFrame(byte[] header, byte[] data) throws IOException {
		BufferedImage img;
		byte[] bmp = new byte[header.length+data.length];
    	System.arraycopy(header, 0, bmp, 0, header.length);
    	System.arraycopy(data, 0, bmp, header.length, data.length);
    	
    	InputStream in = new ByteArrayInputStream(bmp);
		img = ImageIO.read(in);
		imgpanel.setImage(img);
	}
	
	public static void main(String[] args) {
		/*JFrame f = new JFrame("SwingCapture");
		BMPPlayer cf = new BMPPlayer(null);

		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		f.add("Center", cf);
		f.pack();
		f.setSize(new Dimension(320, 240));
		f.setVisible(true);*/
	}

}
